<!-- 
 * @Author: 王坤
 * @LastEditors: Please set LastEditors
 * @Description: 金额
-->
<template>
  <div class="lc-input-money">
    <el-input
      class="lc-input"
      v-model="innerValue"
      v-bind="$attrs"
      @input="inputMoneyFun($event)"
      @change="(v) => $emit('change', v)"
      @blur="(e) => $emit('blur', e)"
      @focus="(e) => $emit('focus', e)"
      @clear="$emit('clear')"
    >
      <!-- 渲染不不正确，先屏蔽 -->
      <!-- <template v-slot:append>
        <component :is="append.componentName" v-for="append in appends" :key="append.id" v-bind="append.props">
        </component>
      </template> -->
    </el-input>
    <div v-if="innerValue" class="lc-input-money__uppercase">
      {{ amountInWords(innerValue) }}
    </div>
  </div>
</template>

<script setup>
import { amountInWords } from '@/utils';
import { ref, watch } from 'vue';
const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: ''
  },
  /* 最大整数位数 */
  maxIntegerDigits: {
    type: [Number, String],
    default: 12
  },
  //最大小数点位数
  maxDecimalDigits: {
    type: [Number, String],
    default: 4
  },
  appends: {
    type: Array,
    default: () => []
  }
});
const emits = defineEmits(['input', 'change', 'blur', 'focus', 'clear', 'update:modelValue']);
const innerValue = ref(props.modelValue);

function inputMoneyFun(value) {
  innerValue.value = formattedAmountFun(value);
  emits('update:modelValue', innerValue.value);
  emits('input', innerValue.value);
}

// 金额格式化
function formattedAmountFun(value) {
  const reg = new RegExp(
    '^-?(\\d{1,' + props.maxIntegerDigits + '})?(\\.\\d{0,' + props.maxDecimalDigits + '})?$'
  );
  if (!reg.test(value)) {
    value = value.slice(0, -1);
  }
  // 先去掉 非(数字|.|-)
  return value.replace(/[^.-\d]/g, '').replace(/(^-?)(0+)(\d+)/, '$1$3').replace(/^(\.)(\d*)/, '0$1$2');
}
watch(
  () => props.modelValue,
  () => (innerValue.value = props.modelValue)
);
</script>
